package org.piggy.server.rpc.core;

import org.piggy.common.async.RequestFuture;
import org.piggy.common.async.Response;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Mediator {

    public static Map<String, MethodBean> methodBeanMap = new HashMap<>();

    public static Response process(RequestFuture requestFuture){
        String path = requestFuture.getPath();
        Response response = new Response();
        MethodBean methodBean = methodBeanMap.get(path);
        if(methodBean != null){
            Object bean = methodBean.getBean();
            Method method = methodBean.getMethod();

            Object[] params = requestFuture.getParam();

//            Class<?>[] paramTypes = method.getParameterTypes();
//            Object [] objects = new Object[paramTypes.length];
//            int i = 0;
//            for(Class<?> c: paramTypes){
//                Object p = JSONObject.parseObject(JSONObject.toJSONString(params[i]),c);
//                objects[i] = p;
//                i++;
//            }

            Object result = null;
            try {
                result = method.invoke(bean, params);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            response.setResult(result);
        }
        response.setId(requestFuture.getId());
        return response;
    }

}
